package com.findyou.utils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.sql.SQLException;

/**
 * @Title: TransactionManager
 * @Author 贾金博
 * @Package com.findyou.utils
 * @Date 2024/11/28 下午5:20
 * @description: 事务管理器
 */
@Component
public class TransactionManager {

    @Autowired
    private ConnectionUtils connectionUtils;

    /**
     * 开启手动去开启事务
     */
    public void beginTransaction() {
        try {
            connectionUtils.getThreadConnection().setAutoCommit(false);
        } catch (SQLException e) {
            e.printStackTrace(); // 打印错误
        }
    }

    /**
     * 提交事务
     */
    public void commit() {
        try {
            connectionUtils.getThreadConnection().commit();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    /**
     * 回滚
     */
    public void rollback() {
        try {
            connectionUtils.getThreadConnection().rollback();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    /**
     * 释放
     */
    public void release() {
        try {
            // 改为之前的 自动的提交
            connectionUtils.getThreadConnection().setAutoCommit(true);
            connectionUtils.getThreadConnection().close(); // 归还到线程池
            connectionUtils.removeThreadConnection(); // 解除线程绑定
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

}
